package com.foolishbird.sdk.ui.activity;

import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.foolishbird.sdk.api.FBSDK;
import com.foolishbird.sdk.assist.CallbackObservable;
import com.foolishbird.sdk.assist.Constant;
import com.foolishbird.sdk.core.HttpEngineApi;
import com.foolishbird.sdk.core.HttpEngineConduits;
import com.foolishbird.sdk.params.bean.AccountInfo;
import com.foolishbird.sdk.params.bean.FloatMenu;
import com.foolishbird.sdk.params.bean.RoleInfo;
import com.foolishbird.sdk.ui.model.ActivityPageInfo;
import com.foolishbird.sdk.ui.model.TabReadStatus;
import com.foolishbird.sdk.ui.view.DialogFactory;
import com.foolishbird.sdk.utils.ResUtils;
import com.foolishbird.sdk.utils.ToolsUtils;
import com.foolishbird.sdk.utils.WL;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.List;


public class FoolishBirdFloatExtensionActivity extends AppBaseActivity implements ViewTreeObserver.OnGlobalLayoutListener,
        View.OnClickListener, AdapterView.OnItemClickListener {

    private static final String TAG = FoolishBirdFloatExtensionActivity.class.getSimpleName();

    private static final String QQ_CUSTOMER_SERVICE = "http://wpd.b.qq.com/page/webchat.html";
    private static final String WECHAT_PUBLIC_NUMBER = "http://www.51wansy.sdkv3.com/";

    private final HashMap<String, String> mLoadUrlStack = new HashMap<String, String>();
//        private Stack<String> mLoadUrlStack=new Stack<>();


    private WebView mContentWebView;
    private ProgressBar mContentProgressBar;
    private TextView userNameText,qufuText,roleId,titleView;
    private ImageView mContentWebViewGoback,mGoBack;
    private GridView mGridView;
    private LinearLayout contentLayout,swithLayout;



    private ViewTreeObserver mViewTreeObserver;



    private ExtensionBarBroadcastReceiver mReceiver;
    private boolean isAnimationLoading = false;
    private List<FloatMenu> floatMenuList;
    private LayoutInflater layoutInflater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutIdentifier("foolishbird_activity_floatextension"));
        floatMenuList =HttpEngineApi.getInstance().getEngineConduits().getPlatformConfigInfo().getFloatingWindow();
        layoutInflater = LayoutInflater.from(this);
        onInitViews();
        mReceiver = new ExtensionBarBroadcastReceiver();
        IntentFilter fliter = new IntentFilter(Constant.LocalIntentAction.DESTROY_FLOAT_EXTENSIONBAR);
        registerReceiver(mReceiver, fliter);
        if(getIntent().getBooleanExtra("custom",false)){
            int index = 0;
            for(int i = 0; i<floatMenuList.size();i++){
                if(floatMenuList.get(i).getId()==7){
                    index = i;
                    break;
                }
            }
            onItemClick(null,null,index,index);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
//        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    }


    private void onInitViews() {
        RoleInfo info = FBSDK.getInstance().getmRoleInfo();
        info = info==null?new RoleInfo():info;
        findViewById(getViewIdentifier("foolishbird_float_hole_layout")).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideFloatExtensionBar(view);
            }
        });
        userNameText = findViewById(getViewIdentifier("foolishbird_float_name"));
        userNameText.setText(info.getRoleName());
        qufuText = findViewById(getViewIdentifier("foolishbird_float_qufu"));
        qufuText.setText(info.getServerName());
        roleId = findViewById(getViewIdentifier("foolishbird_float_roleid"));
        roleId.setText("ID："+info.getRoleId());
        titleView = findViewById(getViewIdentifier("foolishbird_float_title"));
        mGoBack = findViewById(getViewIdentifier("foolishbird_float_back"));
        mGoBack.setOnClickListener(this);
        swithLayout = findViewById(getViewIdentifier("foolishbird_float_switch"));
        swithLayout.setOnClickListener(this);
        contentLayout = findViewById(getViewIdentifier("foolishbird_float_web_layout"));
        mContentProgressBar = (ProgressBar) findViewById(getViewIdentifier("activity_extendsionbar_content_progressbar"));
        mContentWebViewGoback = (ImageView) findViewById(getViewIdentifier("foolishbird_float_back2"));
        mContentWebViewGoback.setOnClickListener(this);
        mContentWebView = (WebView) findViewById(getViewIdentifier("activity_extendsionbar_content_webview"));
        WebSettings webSettings = mContentWebView.getSettings();
        webSettings.setUseWideViewPort(true);
        webSettings.setSupportZoom(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        mContentWebView.setWebChromeClient(new ExtensionBarWebChromeClient());
        mContentWebView.setWebViewClient(new ExtensionBarWebViewClient());
        mContentWebView.addJavascriptInterface(new AndroidJavaScriptInterface(), "h5Game");
        mContentWebView.loadUrl("");
        mViewTreeObserver = userNameText.getViewTreeObserver();
        if (mViewTreeObserver != null && mViewTreeObserver.isAlive()) {
            mViewTreeObserver.addOnGlobalLayoutListener(this);
        }
        mGridView = findViewById(getViewIdentifier("foolishbird_float_gridview"));
        mGridView.setOnItemClickListener(this);
        mGridView.setAdapter(new BaseAdapter() {

            @Override
            public int getCount() {
                return floatMenuList==null?0:floatMenuList.size();
            }

            @Override
            public Object getItem(int i) {
                return floatMenuList.get(i);
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public View getView(int i, View convertView, ViewGroup viewGroup) {
                ViewHolder holder = null;
                if (convertView == null) {
                    int resource = ResUtils.getLayoutIdentifier(FoolishBirdFloatExtensionActivity.this, "fb_float_grid_item");
                    convertView = layoutInflater.inflate(resource, null);
                    holder = new ViewHolder();
                    holder.imageView = (ImageView) convertView.findViewById(ResUtils.getViewIdentifier(FoolishBirdFloatExtensionActivity.this, "float_menu_icon"));
                    holder.text = (TextView) convertView.findViewById(ResUtils.getViewIdentifier(FoolishBirdFloatExtensionActivity.this, "float_menu_name"));
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }
                FloatMenu menu =floatMenuList.get(i);
                Picasso.with(FoolishBirdFloatExtensionActivity.this).load(menu.getIcon()).into(holder.imageView);
                holder.text.setText(menu.getName());
                return convertView;
            }
        });
    }

    class ViewHolder {
        TextView text;
        ImageView imageView;
    }


    @Override
    public void onBackPressed() {
        WL.d(TAG, "onBackPressed  --->"+mLoadUrlStack.size());
        if(contentLayout.getVisibility()==View.VISIBLE){
//            if(!mContentWebView.getUrl().contains("game_id=1")){
            if(mLoadUrlStack.size()<=2){
                mContentWebView.goBack();
                mLoadUrlStack.remove(mContentWebView.getUrl());
                mContentWebView.clearHistory();
                mContentWebView.clearCache(true);
                CookieManager.getInstance().removeAllCookies(null);
                CookieManager.getInstance().flush();
                contentLayout.setVisibility(View.GONE);
            }else{
                mContentWebView.goBack();
                mLoadUrlStack.remove(mContentWebView.getUrl());
            }

//            if(mLoadUrlStack.size()==1){
//
//                mContentWebView.clearHistory();
//                mContentWebView.clearCache(true);
//                CookieManager.getInstance().removeAllCookies(null);
//                CookieManager.getInstance().flush();
//                contentLayout.setVisibility(View.GONE);
//            }
        }else{
            super.onBackPressed();
        }
//        if (isDrawerOpen()) {
//            closeDrawer();
//        } else {token
//            super.onBackPressed();
//        }
    }



    public void hideFloatExtensionBar(View view) {
        WL.d(TAG, "hideFloatExtensionBar  ---> ");
        closeDrawer();
    }






    void checkContentView() {
//        if (mContentView != null && mInflatContentViewStub == null) {
//            mInflatContentViewStub = mContentView.inflate();
//            mContentProgressBar = (ProgressBar) findViewById(getViewIdentifier("activity_extendsionbar_content_progressbar"));
//            mContentTitle = (TextView) findViewById(getViewIdentifier("activity_extendsionbar_content_title"));
//            mContentLocalView = findViewById(getViewIdentifier("activity_extendsionbar_content_local"));
//            mContentRemoteView = findViewById(getViewIdentifier("activity_extendsionbar_content_remote"));
//            mContentWebViewGoback = (ImageButton) findViewById(getViewIdentifier("activity_extendsionbar_content_goback"));
//            mContentWebViewGoback.setOnClickListener(this);
//            mContentWebView = (WebView) findViewById(getViewIdentifier("activity_extendsionbar_content_webview"));
//            WebSettings webSettings = mContentWebView.getSettings();
//            webSettings.setUseWideViewPort(true);
//            webSettings.setSupportZoom(true);
//            webSettings.setAppCacheEnabled(false);
//            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
//            webSettings.setJavaScriptEnabled(true);
//            webSettings.setDomStorageEnabled(true);
//            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//            mContentWebView.setWebChromeClient(new ExtensionBarWebChromeClient());
//            mContentWebView.setWebViewClient(new ExtensionBarWebViewClient());
//            mContentWebView.addJavascriptInterface(new AndroidJavaScriptInterface(), "h5Game");
//
//            mActivityListAdapter = new ActivityListAdapter();
//            mActivityListAdapter.resetItemData(new ArrayList<IActivityContent>(mActivityInfoList));
//            mContentLocalView.setAdapter(mActivityListAdapter);
//            mContentLocalView.setOnItemClickListener(this);
//        }
    }



    private void openDrawer() {

    }



    private void closeDrawer() {
        finish();
//        if (isDrawerOpen() && !isDrawerLoading()) {
//            final Animation closeDrawerAnimation;
//
//            Configuration config = getResources().getConfiguration();
//            if (Configuration.ORIENTATION_PORTRAIT == config.orientation) {
//                final int animRes = getAnimationIdentifier("wan_animation_slide_out_bottom");
//                closeDrawerAnimation = AnimationUtils.loadAnimation(this, animRes);
//            } else {
//                final int animRes = getAnimationIdentifier("wan_animation_slide_out_left");
//                closeDrawerAnimation = AnimationUtils.loadAnimation(this, animRes);
//            }
//
//            closeDrawerAnimation.setAnimationListener(new ExtensionBarDrawerToggle());
////            mDrawerContent.startAnimation(closeDrawerAnimation);
//        }
    }

//    private boolean isDrawerOpen() {
////        return mTabbarView != null && (mInflatTabbarViewStub != null || mInflatContentViewStub != null);
//    }

    private boolean isDrawerLoading() {
        return isAnimationLoading;
    }

    @Override
    public void onGlobalLayout() {
        WL.d(TAG, "onGlobalLayout  ---> ");
        openDrawer();
    }

    @Override
    public void onClick(View v) {
        if(v==mContentWebViewGoback){
            onBackPressed();
//            if (mContentWebView != null) {
//                mContentWebView.goBack();
////                if (mContentWebView.canGoBack()) {
////                    final String url = mContentWebView.getUrl();
////                    WL.d(TAG, "goback ----> url: " + url);
////                    mLoadUrlStack.remove(url);
////                    mContentWebView.goBack();
////                }else {
////                    onBackPressed();
////                }
//            }
        }else if (v==mGoBack){
            onBackPressed();
        }else if(v==swithLayout){
            Log.d("test","swichAccountCall");
//            WanSDK.getInstance().logout();
            HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
            wanSDKDataDao.writeAutoLogin(false);
//            WanSDK.getInstance().login();
//
            FBSDK.getInstance().logout();
//            JHToolsSDK.getInstance().onSwitchAccount();
//            login();
            FBSDK.getInstance().closeWindow();
            CallbackObservable.getInstance().callResponseResult(Constant.CallType.CALL_LOGIN,Constant.LoginState.SWITH_ACCOUNT,"","");
            finish();
        }

    }



    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         FloatMenu menu = floatMenuList.get(position);
         if(TextUtils.isEmpty(menu.getLink())){
             Toast.makeText(FoolishBirdFloatExtensionActivity.this,"敬请期待",Toast.LENGTH_SHORT).show();
             return;
         }
         String append=menu.getLink().contains("?")?"&":"?";
         append+="token="+HttpEngineApi.getInstance().getEngineConduits().readCurrentLoginUserTicket()
                 +"&game_id="+ FBSDK.getInstance().getGameId();
//         if(mContentWebView.)
        mContentWebView.loadUrl(menu.getLink()+append);
        contentLayout.setVisibility(View.VISIBLE);
        titleView.setText(menu.getName());
//        final ActivityPageInfo activityPageInfo = new ActivityPageInfo();
//        activityPageInfo.setCurrentUrlIndex(position);
//        activityPageInfo.setActivityPageUrlList(mActivityListAdapter.getActivityDetailList());
//        ActivityCenterActivity.forwardActivityCenterActivity(this, activityPageInfo);
    }

    private class ExtensionBarWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!TextUtils.isEmpty(title)) {
//                if(title.contains("weixin")){
//                    mContentTitle.setText("正在前往微信");
//                }else{
//                    mContentTitle.setText(title);
//                }
            } else {
//                mContentTitle.setText(getStringIdentifier("hnssn_float_message"));
            }

        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (mContentProgressBar != null) {
                if (newProgress == 100) {
                    mContentProgressBar.setVisibility(View.GONE);
                } else {
                    if (View.VISIBLE != mContentProgressBar.getVisibility()) {
                        mContentProgressBar.setVisibility(View.VISIBLE);
                    }
                    mContentProgressBar.setProgress(newProgress);
                }

            }
            super.onProgressChanged(view, newProgress);
        }
    }

    private class ExtensionBarWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            WL.d(TAG, "shouldOverrideUrlLoading ---->url: " + url);

            if (url.startsWith(QQ_CUSTOMER_SERVICE)) {
                try {
                    String qq = getValueByName(url, "nameAccount");

                    WL.d(TAG, "shouldOverrideUrlLoading ---->qq: " + qq);

                    String localUrl = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq;
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(localUrl)));
                } catch (ActivityNotFoundException e) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                }
            } else if (url.startsWith(WECHAT_PUBLIC_NUMBER)) {
                if (ToolsUtils.isInstallWeixin(getApplicationContext())) {
                    String originalAppId = getValueByName(url, "id");
                    String appId = getValueByName(url, "appId");

                    ToolsUtils.startWeChatPublicNumber(getApplicationContext(), appId, originalAppId);
                } else {
                    String message = getString(getStringIdentifier("hnssn_hint_wechat_uninstall"));
                    DialogFactory.createConfirmDialog(FoolishBirdFloatExtensionActivity.this, message).show();
                }
            }else if (url.startsWith("weixin://")){
                startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),123);
            }
            else {
                if (mContentWebView != null) {
                    mContentWebView.loadUrl(url);
                }


            }

            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            WL.d(TAG, "onPageFinished ----> url: " + url);
            mLoadUrlStack.put(url, url);
//            mLoadUrlStack.push(url);
//            if (mLoadUrlStack.isEmpty()) {
//                mContentWebViewGoback.setVisibility(View.GONE);
//            } else {
//                mContentWebViewGoback.setVisibility(View.VISIBLE);
//            }
        }
    }
    public static String getValueByName(String url, String name) {
        String result = "";
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }

    private class ExtensionBarDrawerToggle implements Animation.AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {
            WL.d(TAG, "onDrawerOpened ----> ");
            isAnimationLoading = true;
            if (mViewTreeObserver != null && mViewTreeObserver.isAlive()) {
                mViewTreeObserver.removeGlobalOnLayoutListener(FoolishBirdFloatExtensionActivity.this);
            }
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            WL.d(TAG, "onDrawerClosed ----> ");
            isAnimationLoading = false;
            finish();
            overridePendingTransition(0, 0);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    }

    private class ExtensionBarBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                String action = intent.getAction();
                if (TextUtils.equals(action, Constant.LocalIntentAction.DESTROY_FLOAT_EXTENSIONBAR)) {
                    closeDrawer();
                }
            }
        }
    }

    private class AndroidJavaScriptInterface {

        @JavascriptInterface
        public void readCall(String json) {
            JsonParser jsonParser = new JsonParser();
            JsonElement jsonElement = jsonParser.parse(json);
            if (jsonElement.isJsonArray()) {
                JsonArray jsonArray = jsonElement.getAsJsonArray();
                for (int index = 0; index < jsonArray.size(); index++) {
                    JsonElement jsonObject = jsonArray.get(index);
                    final TabReadStatus status = new Gson().fromJson(jsonObject, TabReadStatus.class);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            setTabDividerRedDotVisible(status.getPosition() - 1, status.isReadStatus());
                        }
                    });
                }

            }
        }
        @JavascriptInterface
        public void shareCall(String json) {

            Gson gson = new Gson();
            ActivityPageInfo activityPageInfo =gson.fromJson(json,ActivityPageInfo.class);

            ActivityCenterActivity.forwardActivityCenterActivity(FoolishBirdFloatExtensionActivity.this, activityPageInfo);
        }

        @JavascriptInterface
        public void swichAccountCall(String json){
            Log.d("test","swichAccountCall");
//            WanSDK.getInstance().logout();
            HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
            wanSDKDataDao.writeAutoLogin(false);
//            WanSDK.getInstance().login();
//
//            WanSDK.getInstance().logout();
//            JHToolsSDK.getInstance().onSwitchAccount();
//            login();
            CallbackObservable.getInstance().callResponseResult(Constant.CallType.CALL_LOGIN,Constant.LoginState.SWITH_ACCOUNT,"","");
            finish();
        }

        @JavascriptInterface
        public void changePwdCall(String json){
            Log.d("test","changePwdCall");
            HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
            AccountInfo info = wanSDKDataDao.findUserAccountByUserId(wanSDKDataDao.readCurrentLoginUserUID());
            if(info!=null){
                info.setPassword("");
                wanSDKDataDao.saveUserAccount(info);
            }
            wanSDKDataDao.writeAutoLogin(false);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==123){
            if(mContentWebView.canGoBack()){
                mContentWebView.goBack();
            }
        }
    }
}
